package com.ityuhao.tech.concurrency.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RedisLockDemo {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    public void demo1() throws Exception{
        Boolean b1= redisTemplate.opsForValue().setIfAbsent("key", "1", 5, TimeUnit.SECONDS);
        log.info(b1.toString());
        Boolean b2 = redisTemplate.opsForValue().setIfAbsent("key", "2", 5, TimeUnit.SECONDS);
        log.info(b2.toString());
        Thread.sleep(6000);
        Boolean b3 = redisTemplate.opsForValue().setIfAbsent("key", "3", 5, TimeUnit.SECONDS);
        log.info(b3.toString());
        redisTemplate.delete("key");
        Boolean b4 = redisTemplate.opsForValue().setIfAbsent("key", "4", 5, TimeUnit.SECONDS);
        log.info(b4.toString());
    }

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public void demo2() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}", count);
    }

    public Long count = 1L;

    private void add() {
        RLock lock = redissonClient.getLock("lock");
        //加锁
        lock.lock();
        try{
            // 业务
            count++;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }

}
